package com.meiwenhui.sishuwujing.adapter;

import java.util.List;

import net.tsz.afinal.FinalHttp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

import com.meiwenhui.sishuwujing.entities.Catalogue;

public class MainGridViewAdapter extends CursorAdapter {

	private Context context;

	private void syncCategories() {

		FinalHttp finalHttp = new FinalHttp();
		Object content = finalHttp.getSync("http://127.0.0.1/sishuwujing/index.php");
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(content.toString());

			for (int i = 0; i < jsonArray.length(); i++) {
				Object _object = jsonArray.get(i);
				JSONObject _jsonObject = new JSONObject(_object.toString());
				Catalogue category = new Catalogue();
				category.setName(_jsonObject.get("name").toString());
				category.save(context);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	public MainGridViewAdapter(Context context, boolean autoRequery) {
		this(context, null, autoRequery);
		this.context = context;
		List<Catalogue> books = Catalogue.objects(context).toList();
		if (books.size() == 0) {
			syncCategories();
		}
	}

	public MainGridViewAdapter(Context context, Cursor c, boolean autoRequery) {
		super(context, c, autoRequery);
		this.context = context;

		// TODO Auto-generated constructor stub
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {

	}

}
